<!-- 分页查询
<pager-query :pager=[分页对象] @query=[列表查询方法] />
-->

<template>
  <div class="mod-paging-query fn-clear">
    <el-pagination
      v-if="showPage"
      class="fn-right troila-page1"
      background
      :layout="layOut"
      :total="pager[props.total]"
      :current-page.sync="pager[props.page]"
      :page-size="pager[props.limit]"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="onChangeSize"
      @current-change="onChangePage"
    ></el-pagination>
    <span
      v-if="refresh"
      class="btn-refresh fn-right"
      title="刷新"
      @click="$emit('query')"
    >
      <i class="fas fa-redo"></i>
    </span>
  </div>
</template>

<script>
export default {
  name: 'PagingQuery',
  props: {
    pager: {
      type: Object,
      required: true,
    },
    refresh: {
      type: Boolean,
    },
    props: {
      type: Object,
      required: false,
      default: () => ({
        page: 'page', // 第几页
        limit: 'size', // 显示条数
        total: 'total', // 总记录条数
      }),
    },
    layOut: {
      type: String,
      default: 'prev, pager, next',
    },
  },
  // 设置绑定参数
  model: {
    prop: 'pager',
    event: 'setPager',
  },
  data() {
    return {
      showPage: true,
    }
  },
  computed: {
    total() {
      return this.pager[this.props.total] || 0
    },
    // 检测获取到的数据是否为空
    isEmptyList() {
      return (
        Math.ceil(this.pager[this.props.total] / this.pager[this.props.limit]) <
        this.pager[this.props.page]
      )
    },
  },
  watch: {
    total() {
      // 存在记录但未获取到数据时, 重新请求
      if (this.pager[this.props.page] > 1 && this.isEmptyList) {
        this.$emit(
          'setPager',
          Object.assign(this.pager, {
            [this.props.page]: this.pager[this.props.page] - 1,
          })
        )
        this.$emit('query')
      }
    },
  },
  methods: {
    // 每页条数
    onChangeSize(rows) {
      const temp = {
        [this.props.limit]: rows,
        // 当显示条数小于或等于总条数时，重置页数
        [this.props.page]: rows <= this.total ? 1 : this.pager[this.props.page],
      }

      this.$emit('setPager', Object.assign(this.pager, temp))
      // 触发父组件查询请求
      this.$emit('query')
    },
    // 翻页
    onChangePage(page) {
      this.$emit(
        'setPager',
        Object.assign(this.pager, { [this.props.page]: page })
      )
      this.$emit('query')
    },
    //重置当前页
    handlePage(page) {
      this.pager.page = page
    },
  },
}
</script>
<style scoped>
.mod-paging-query {
  margin: 0 0 8px;
  text-align: left;
}
.troila-page1 >>> li,
.troila-page1 >>> button.btn-prev,
.troila-page1 >>> button.btn-next {
  line-height: 30px;
}
</style>
